package com.vsd.service.impl;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.dialet.PaginationSupport;
import com.demo.util.DateUtil;
import com.demo.util.MathUtil;
import com.demo.util.SqlUtils;
import com.demo.util.StringUtil;
import com.shopcart.daoEx.model.StoreGoodsEx;
import com.shopcart.domain.StoreGoods;
import com.vsd.repository.StoreGoodsRepository;
import com.vsd.service.StoreGoodsService;
import com.zy.store.proto.MOAppStore.MStoreGoodsCate;
import com.zy.store.proto.MOAppStore.MStoreGoodsCate.Builder;
import com.zy.store.proto.MOAppStore.MStoreGoodsMini;
import com.zy.store.proto.MOAppStore.MTgGoodsMini;
import com.zy.store.proto.MOAppStore.MTgGoodsMiniList;

@Service
@Transactional
public class StoreGoodsServiceImpl implements StoreGoodsService {
	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory
			.getLogger(StoreGoodsServiceImpl.class);
	@Autowired
	private  StoreGoodsRepository storeGoodsRepository;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public StoreGoods save(StoreGoods goods){
		return storeGoodsRepository.save(goods);
	}
	
	@Override
	public int updateByPrimaryKeySelective(StoreGoods goods){
		String sql;
		try {
			sql = SqlUtils.update(goods, true, "where id='"+goods.getId()+"'");
		} catch (Exception e) {
			return 0;
		}
		return jdbcTemplate.update(sql);
	}
	
	@Override
	public Page<StoreGoods> findAll(Pageable p){
		return storeGoodsRepository.findAll(p);
	}
	
	@Override
	public List<StoreGoodsEx> findExList(String areaCode,String cateCode,String name,String storeId, Integer type,Integer page,Integer limit){
		String sql ="select sg.*,c.name as cityName,s.name as storeName,sgc.name as cateName from s_store_goods sg "
				+ "left join s_store s on sg.store_id = s.id "
				+ "left join f_city c on s.area_code = c.code "
				+ "left join s_store_goods_category sgc on sgc.id = sg.cate_code "
				+ "where sg.is_del = 0";
		if(StringUtils.isNoneBlank(areaCode)){
			sql+=" and s.area_code like '"+areaCode+"%'";
		}
		if(StringUtils.isNoneBlank(cateCode)){
			sql+=" and sg.cate_code = '"+cateCode+"'";
		}
		if(StringUtils.isNoneBlank(name)){
			sql+=" and sg.name like '%"+name+"%'";
		}
		if(StringUtils.isNoneBlank(storeId)){
			sql+=" and sg.store_id ='"+storeId+"'";
		}
		if(type!=null){
			sql+=" and sg.type ="+type+"";
		}
		sql+=" order by sg.create_time desc";
		
		int c = jdbcTemplate.queryForObject("select count(1) from ("+ sql+") a_cnt", Integer.class);
		PaginationSupport.getContext().setTotalCount(c);
		
		sql+=" limit "+(page*limit)+","+limit;
		
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		List<StoreGoodsEx> exList = new ArrayList<>();
		for (Map<String, Object> map : maps) {
			StoreGoodsEx ex = new StoreGoodsEx();
			SqlUtils.transMap2Bean2(map, ex);
			exList.add(ex);
		}
		return exList;
	}
	
	@Override
	public Page<StoreGoods> findByNameLike(String search,Pageable p){
		return storeGoodsRepository.findByNameLike(search,p);
	}
	
	@Override
	public MTgGoodsMiniList.Builder findGuess(String lat,String lng) {
		MTgGoodsMiniList.Builder ret = MTgGoodsMiniList.newBuilder();

		String sql = "select sg.id as goodsId,sg.`name` as goodsName,sg.img,sg.now_price,sg.sell_base	,s.`name` as storeName ";
		
		if(StringUtils.isNoneBlank(lat)&&StringUtils.isNoneBlank(lng)){
			sql+=",getDistance(s.lng,s.lat,"+lng+","+lat+") as distance";
		}
		
		sql+= "	,(select count(1) from s_order o where o.store_id = s.id and o.state=4) as sellCnt"
			+ "	from  s_store_goods sg "
			+ "	left join s_store s on s.id = sg.store_id"
			+ "	where s.is_online=1 and s.closed=0 and sg.is_online=1 and sg.is_del=0   order by rand()"
			+ " limit 0,20";
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		
		for (Map<String, Object> map : maps) {
			MTgGoodsMini.Builder mini = MTgGoodsMini.newBuilder();
			mini.setDistance(MathUtil.getDistanceStr(StringUtil.obj2String(map.get("distance"))));
			mini.setGoodsName(StringUtil.obj2String(map.get("goodsName")));
			mini.setId(StringUtil.obj2String(map.get("goodsId")));
			mini.setImg(StringUtil.obj2String(map.get("img")));
			mini.setPrice(StringUtil.obj2String(map.get("now_price")));
			int sellBase = map.get("sell_base")==null?0:new Integer(map.get("sell_base").toString());
			int sellCnt = map.get("sellCnt")==null?0:new Integer(map.get("sellCnt").toString());
			mini.setSellCnt((sellBase+sellCnt)+"");
			mini.setStoreName(StringUtil.obj2String(map.get("storeName")));
			ret.addList(mini);
		}
		
		
		return ret;
	}


	@Override
	public Collection<StoreGoods> findByStoreIdAndType(String storeId,
			Integer type) {
		// TODO Auto-generated method stub
		return storeGoodsRepository.findByStoreIdAndType(storeId, type,new Sort(Direction.DESC,"sort"));
	}


	@Override
	public Collection<StoreGoods> findByStoreIdAndCateCodeAndType(
			String storeId, String cateId, Sort sort) {
		// TODO Auto-generated method stub
		return storeGoodsRepository.findByStoreIdAndIsOnlineAndIsDelAndCateCodeAndTypeOrType(storeId,1,0, cateId, 1, 3, sort);
	}


	@Override
	public MStoreGoodsCate.Builder findAppList(String storeId, String cateId,String cateName) {
		MStoreGoodsCate.Builder ret = MStoreGoodsCate.newBuilder();
		ret.setId(cateId);
		ret.setTitle(cateName);
		String start = DateUtil.getFirstOfMonth()+" 00:00:00";
		String end = DateUtil.dateToStr(new Date(),"yyyy-MM-dd")+" 23:59:59";
		
		String sql = "select sg.*,(select count(1) from s_order_detail od "
				+ "left join s_order o on od.order_id = o.id	where od.goods_id = sg.id and o.state = 4 and o.create_time >= '"+start
				+"' and o.create_time <= '"+end+"') as sellCnt"
				+ " from s_store_goods sg where sg.type!=2 and sg.is_del=0 and sg.is_online =1 and sg.store_id='"+storeId+"' and sg.cate_code='"+cateId
				+"' ORDER BY sg.sort desc";
		
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		
		for (Map<String, Object> map : maps) {
			MStoreGoodsMini.Builder m = MStoreGoodsMini.newBuilder();
			m.setId(StringUtil.obj2String(map.get("id")));
			m.setImg(StringUtil.obj2String(map.get("img")));
			m.setName(StringUtil.obj2String(map.get("name")));
			m.setPrice(StringUtil.obj2String(map.get("now_price")));
			m.setSellCnt(map.get("sellCnt")==null?0:new Integer(map.get("sellCnt").toString()));
			m.setType(map.get("type")==null?1:new Integer(map.get("type").toString()));
			ret.addList(m);
		}
		
		return ret;
	}
	
	public StoreGoods findById(String id){
		return storeGoodsRepository.findOne(id);
	}


	@Override
	public Collection<StoreGoods> findByIds(String ids) {
		return storeGoodsRepository.findByIdIn(Arrays.asList(ids.split(",")));
	}

	@Override
	public Builder findAppListByType(String storeId, Integer type) {
		MStoreGoodsCate.Builder ret = MStoreGoodsCate.newBuilder();
		String start = DateUtil.getFirstOfMonth()+" 00:00:00";
		String end = DateUtil.dateToStr(new Date(),"yyyy-MM-dd")+" 23:59:59";
		
		String sql = "select sg.*,(select count(1) from s_order_detail od "
				+ "left join s_order o on od.order_id = o.id	where od.goods_id = sg.id and o.state = 4 and o.create_time >= '"+start
				+"' and o.create_time <= '"+end+"') as sellCnt"
				+ " from s_store_goods sg where  sg.is_del=0 and sg.is_online =1 and sg.store_id='"+storeId+"' and sg.type="+type
				+" ORDER BY sg.sort desc";
		
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		
		for (Map<String, Object> map : maps) {
			MStoreGoodsMini.Builder m = MStoreGoodsMini.newBuilder();
			m.setId(StringUtil.obj2String(map.get("id")));
			m.setImg(StringUtil.obj2String(map.get("img")));
			m.setName(StringUtil.obj2String(map.get("name")));
			m.setPrice(StringUtil.obj2String(map.get("now_price")));
			m.setSellCnt(map.get("sellCnt")==null?0:new Integer(map.get("sellCnt").toString()));
			m.setType(map.get("type")==null?1:new Integer(map.get("type").toString()));
			ret.addList(m);
		}
		return ret;
	}
	@Override
	public JSONObject findList(String storeId, String cateId,String cateName){
		JSONObject ret = new JSONObject();
		ret.put("cateId", cateId);
		ret.put("cateName", cateName);
		JSONArray list = new JSONArray();
		String start = DateUtil.getFirstOfMonth()+" 00:00:00";
		String end = DateUtil.dateToStr(new Date(),"yyyy-MM-dd")+" 23:59:59";
		
		String sql = "select sg.*,(select count(1) from s_order_detail od "
				+ "left join s_order o on od.order_id = o.id	where od.goods_id = sg.id and o.state = 4 and o.create_time >= '"+start
				+"' and o.create_time <= '"+end+"') as sellCnt"
				+ " from s_store_goods sg where sg.is_del=0 and sg.is_online =1 and sg.store_id='"+storeId+"' and sg.cate_code='"+cateId
				+"' ORDER BY sg.sort desc";
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		
		for (Map<String, Object> map : maps) {
			JSONObject m = new JSONObject();
			m.put("id", map.get("id"));
			m.put("img", map.get("img"));
			m.put("name", map.get("name"));
			m.put("price", map.get("now_price"));
			m.put("type", map.get("type")==null?1:new Integer(map.get("type").toString()));
			m.put("sellCnt", map.get("sellCnt")==null?0:new Integer(map.get("sellCnt").toString()));
			list.add(m);
		}
		ret.put("goodsList", list);
		return ret;
	}
	
}
